<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>11 自定义鼠标右键行为</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    ul {
      border: solid 1px gray;
      width: 120px;
      list-style-type: none;
    }

    li:hover {
      background: lightgreen;
    }

    a {
      text-decoration: none;
    }

    .contextmenu {
      position: fixed;
      left: 0;
      top: 0;
    }

    .tit {
      font-size: 22px;
      text-shadow: 3px 3px 5px pink;
    }
  </style>
</head>

<body>
  <span class='tit'>鼠标右键查看效果</span>
  <script>
    window.oncontextmenu = function (ev) {
      ev.preventDefault();
      let contextmenu = document.querySelector(".contextmenu");
      if (!contextmenu) {
        contextmenu = document.createElement("div");
        contextmenu.className = "contextmenu";
        contextmenu.innerHTML = `
    <ul class="menu">
      <li><a class='link' href="#1">开始菜单</a></li>
      <li><a class='link' href="#2">关于我们</a></li>
      <li><a class='link' href="#3">企业动态</a></li>
      <li><a class='link' href="#4">联系我们</a></li>
    </ul>
    `;
        document.body.appendChild(contextmenu);
      }
      // 控制右键位置
      contextmenu.style.top = ev.clientY + 'px';
      contextmenu.style.left = ev.clientX + 'px';
    }
    window.onclick = function (ev) {
      let target = ev.target,
        targetName = target.targetName;
      // 点击contextmenu不做任何处理
      if (targetName === 'LI') {
        target = target.parentNode,
          targetName = target.targetName;
      }
      if (targetName === 'UL' && targetName.parentNode.className == 'contextmenu') {
        return;
      }
      // 点击空白处让右键菜单消失
      let contextmenu = document.querySelector(".contextmenu");
      if (contextmenu) {
        document.body.removeChild(contextmenu);
      }
    }
  </script>
</body>

</html>